<template>
  <div>
    <el-tabs v-model="activeKey" @tab-click="handleTab">
      <el-tab-pane label="日汇总" name="1"> </el-tab-pane>
      <el-tab-pane label="月汇总" name="2"></el-tab-pane>
    </el-tabs>
    <el-card style="min-width: 1200px">
      <div class="tableSelectWrap">
        <el-form ref="dealCollectForm" :model="commandForm" label-width="100px">
          <el-row>
            <el-col :span="7">
              <el-form-item label="选择时间" prop="date" v-if="activeKey == 1">
                <el-date-picker
                  style="width: 100%"
                  v-model="commandForm.date"
                  type="month"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  placeholder="选择时间"
                  value-format="yyyy-MM"
                  :picker-options="pickerOptions"
                  :clearable="false"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="选择时间" prop="date" v-if="activeKey == 2">
                <el-date-picker
                  style="width: 100%"
                  v-model="commandForm.date"
                  type="year"
                  placeholder="选择时间"
                  value-format="yyyy"
                  :clearable="false"
                  :picker-options="pickerOptions"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="7" :offset="1">
              <el-form-item label="支付渠道" prop="channel">
                <el-select
                  v-model="commandForm.channel"
                  class="leftSelect"
                  style="width: 100%"
                  placeholder="请选择支付渠道"
                  @change="handleChannel"
                >
                  <el-option
                    v-for="(item, index) of payChannel"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item
                label=""
                prop="payType"
                label-width="0"
                v-if="commandForm.channel"
              >
                <el-select
                  class="rightSelect"
                  v-model="commandForm.payType"
                  style="width: 100%"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, index) of payChannelTypeList"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item> -->
            </el-col>
            <el-col :span="6" :offset="1" style="min-width: 170px">
              <el-button class="width120" @click="this.resetFields"
                >重置</el-button
              >
              <el-button type="primary" class="width120" @click="handleQuery"
                >查询</el-button
              >
            </el-col>
            <!-- <el-col :span="7" :offset="1">
              <el-form-item label="交易类型" prop="transactioType">
                <el-select
                  v-model="commandForm.transactioType"
                  class="leftSelect"
                  style="width: 100%"
                  placeholder="请选择交易类型"
                >
                  <el-option
                    v-for="item of transactiotypeList"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
          </el-row>
          <!-- <el-row>
            <el-col :span="6" style="min-width: 170px">
              <el-button class="width120" @click="this.resetFields"
                >重置</el-button
              >
              <el-button type="primary" class="width120" @click="handleQuery"
                >查询</el-button
              >
            </el-col>
          </el-row> -->
        </el-form>
      </div>
    </el-card>
    <el-card
      class="textBox"
      style="min-width: 1200px; margin-bottom: -5px; margin-top: 15px"
    >
      <span class="numBox">
        <span>{{ this.activeKey == "1" ? "月收入总额" : "年收入总额" }}</span>
        <span class="symbol">￥</span>
        <span class="num">{{ info.totalIncome || 0.0 }}</span>
      </span>
      <span class="numBox">
        <span>{{ this.activeKey == "1" ? "月支出总额" : "年支出总额" }}</span>
        <span class="symbol">￥</span>
        <span class="num">{{ info.totalPayout || 0.0 }}</span>
      </span>
      <!-- <span class="numBox">
        <span>退款总额</span>
        <span class="symbol">￥</span>
        <span class="num">{{info.refundAmount || 0.00}}</span>
      </span> -->
    </el-card>
    <el-card style="margin-top: 20px; min-width: 1200px">
      <div class="switch">
        <div>
          <el-switch v-model="isFixedTableH" inactive-text="固定表头">
          </el-switch>
          <!-- <el-switch
            class="ml"
            v-model="onlyShowSelf"
            @change="queryFn()"
            inactive-text="仅展示商户自身数据"
          >
          </el-switch> -->
        </div>
        <!-- <el-button type="primary" style="width: 168px">{{activeKey==1?'日报表下载':'月报表下载'}}</el-button> -->
      </div>
      <el-table :data="dataList" :height="fixedTableHeight">
        <template slot="empty">
          <el-empty
            :image="require('@/assets/imgs/middleWork/k1.png')"
            :image-size="80"
            description="暂无相关数据"
          ></el-empty>
        </template>
        <el-table-column
          show-overflow-tooltip
          prop="groupTime"
          align="center"
          label="日期"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{ scope.row.groupTime ? scope.row.groupTime : "-" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="fmtTotalIncomeAmount"
          align="center"
          sortable
          label="收入/元"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{
                Number(scope.row.fmtTotalIncomeAmount)
                  ? scope.row.fmtTotalIncomeAmount
                  : "0.00"
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="fmtTotalPayoutAmount"
          align="center"
          sortable
          label="支出/元"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{
                Number(scope.row.fmtTotalPayoutAmount)
                  ? scope.row.fmtTotalPayoutAmount
                  : "0.00"
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="fmtTotalFeeAmount"
          align="center"
          sortable
          label="渠道手续费/元"
        >
          <template slot-scope="scope">
            <div
              style="
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{
                Number(scope.row.fmtTotalFeeAmount)
                  ? scope.row.fmtTotalFeeAmount
                  : "0.00"
              }}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column show-overflow-tooltip
          prop="address"
          sortable
          align="center"
          label="手续费/元"
        >
        </el-table-column> -->
        <el-table-column
          show-overflow-tooltip
          prop="address"
          align="center"
          :label="activeKey == 1 ? '日报表' : '月报表'"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.groupTime == newDate">当日报表于次日生成</div>
            <div v-else>
              <div
                v-if="
                  !Number(scope.row.totalIncomeAmount) &&
                  !Number(scope.row.totalPayoutAmount)
                "
              >
                -
              </div>
              <el-button
                v-else
                @click="downFn(scope.row)"
                v-throttle="1000"
                type="primary"
                class="tableBtn"
                >下载</el-button
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          v-if="activeKey == '1'"
          prop="address"
          align="center"
          label="渠道对账单"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.groupTime == newDate">
              当日报表于次日12:00生成
            </div>
            <div v-else>
              <div
                v-if="
                  !Number(scope.row.totalIncomeAmount) &&
                  !Number(scope.row.totalPayoutAmount)
                "
              >
                -
              </div>
              <el-button
                v-else
                @click="channelDownFn(scope.row)"
                v-throttle="1000"
                type="primary"
                class="tableBtn"
                :disabled="scope.row.channelBillFileCreated == false"
                >下载</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      class="cardDialog"
      :visible.sync="chargeDia"
      :show-close="false"
      width="480px"
      top="30vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="tip">选择需要下载的渠道对账单</div>
      <el-form ref="form" :rules="rules" :model="form">
        <el-form-item prop="dChannel" label-position="top">
          <el-select
            v-model="form.dChannel"
            placeholder="请选择"
            class="width512"
          >
            <!-- <el-option
              label="汇付"
              value="ada"
              v-if="getUserInfo().userType != 'sub_admin'"
            >
            </el-option>
            <el-option label="微信" value="wechat"> </el-option>
            <el-option label="支付宝" value="ali"> </el-option>
            <el-option label="银联" value="union"> </el-option>
            <el-option label="抖音" value="douyin"> </el-option>
            <el-option label="银盛" value="yse"> </el-option> -->
            <el-option
              v-for="(key,idx) in Object.keys(options)"
              :key="idx"
              :label="options[key]"
              :value="key"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cencelReset">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { setTabIndex, getTabIndex } from "@/utils/public";
import { getUserInfo } from "@/utils/public";
import mixin from "@/mixins/mixin";
export default {
  mixins: [mixin],
  name: "dealCollect",
  data() {
    return {
      chargeDia: false,
      curRow: "",
      form: {
        dChannel: "",
      },
      rules: {
        dChannel: [
          { required: true, message: "请选择渠道", trigger: "change" },
        ],
      },
      options: [
        {
          value: "ada",
          label: "汇付",
        },
        {
          value: "wechat",
          label: "微信",
        },
        {
          value: "ali",
          label: "支付宝",
        },
      ],
      // hasTransactioType: false, //是否选择了交易类型
      pickerOptions: {
        disabledDate: (time) => {
          return this.checkTime(time);
        },
      },
      onlyShowSelf: false,
      newDate: this.$moment(new Date()).format("YYYY-MM-DD"),
      mixinViewModuleOptions: {
        getDataListURL: "/api/orderStream/gatherOrderByDay",
        createdIsNeed: false,
      },
      activeKey: getTabIndex(),
      commandForm: {
        onlyShowSelft: "",
        date: "",
        channel: "",
        // payType: "",
        // transactioType: "",
      },
      dataList: [],
      payChannel: [],
      // payChannel: this.$store.state.channelList,

      transactiotypeList: [
        { id: 1, label: "所有", value: "" },
        { id: 2, label: "支付", value: "order" },
        { id: 3, label: "退款", value: "refund" },
        { id: 4, label: "余额结算", value: "settle" },
        { id: 5, label: "企业付款", value: "transfer" },
        // { id: 6, label: "提现", value: "withdrawal" },
        { id: 6, label: "充值", value: "charge" },
      ],
      payChannelType: this.$store.state.channelListType,
      payChannelTypeList: [],
      info: {},
    };
  },
  created() {
    if (!this.commandForm.channel) {
      this.payChannelTypeList = [{ label: "所有", value: "" }];
    }
    this.getChannelList();
  },
  mounted() {
    this.handleTab();
  },
  watch: {
    "$store.state.testLine": {
      handler() {
        if (this.$route.name == this.$options.name) {
          this.handleTab();
        }
      },
    },
    deep: true,
  },
  methods: {
    getUserInfo,
    getTabIndex,
    getChannelList() {
      this.$http.get("/api/dict/channelList").then((res) => {
        if (res.code === "0000") {
          var a = [{ label: "所有", value: "" }];
          var b = a.concat(res.data);
          this.payChannel = b;
        }
      });
    },
    cencelReset() {
      this.chargeDia = false;
      // this.$refs.form.resetFields(); //重置状态
    },
    handleSubmit() {
      // console.log(this.curRow.channel)
      if (this.curRow && this.curRow.channel == "") {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.downFile(this.form.dChannel);
          } else {
            return false;
          }
        });
      } else {
        this.downFile(this.curRow.channel);
      }
    },
    downFile(channel) {
      console.log(this.curRow);
      this.$http
        .post(`/api/bill/downloadCenter/createChannelBill`, {
          billDate: this.curRow.groupTime,
          payformChannel: channel,
          memberId: "",
        })
        .then((res) => {
          if (res.code === "0000") {
            this.$message.success("已添加到下载中心！");
            this.cencelReset();
          }
        });
    },
    //重置操作
    resetFields() {
      this.resetForm("dealCollectForm");
      if (this.activeKey == "1") {
        this.commandForm.date = this.$moment().format("YYYY-MM");
      } else {
        this.commandForm.date = this.$moment().format("YYYY");
      }
      // this.commandForm = {
      //   onlyShowSelft: "",
      //   date: "",
      //   channel: "",
      //   payType: "",
      //   transactioType: "",
      // };
    },
    checkTime(time) {
      // let t = new Date().getDate();
      // 如果想包含本月本月 - 8.64e7 * t 就不需要了，
      // 如果想之前的不能选择把 > 换成 <
      return time.getTime() > Date.now();
    },
    queryFn() {
      if (this.onlyShowSelf) {
        this.commandForm.onlyShowSelft = true;
      } else {
        this.commandForm.onlyShowSelft = false;
      }
      this.handleQuery();
    },
    downFn(row) {
      this.$http
        .post(`/api/bill/downloadCenter/createYuncnBill`, {
          billDate: row.groupTime,
          dataType: "current_member",
          billType: "yuncnpay",
          memberId: "",
        })
        .then((res) => {
          if (res.code === "0000") {
            this.$message.success("已添加到下载中心！");
          }
        });
    },
    channelDownFn(row) {
      // console.log(row.channel)
      //未选择渠道
      if (row.channel == "") {
        this.options = row.channelMap;
        this.curRow = row;
        this.chargeDia = true;
      } else {
        //已选渠道
        this.curRow = row;
        this.handleSubmit();
      }
      // this.curRow = row;
      // console.log(this.curRow)
    },
    handleTab() {
      setTabIndex(this.activeKey);
      this.payChannelTypeList = [];
      this.resetFields();
      this.handleQuery();
    },
    handleQuery() {
      // if (this.commandForm.transactioType !== "") {
      //   this.hasTransactioType = true;
      // } else {
      //   this.hasTransactioType = false;
      // }

      if (this.activeKey == "1") {
        this.getDayList();
      } else {
        this.getMonthList();
      }
    },
    handleChannel(val) {
      if (val) {
        this.payChannelTypeList = this.payChannelType[val];
        //console.log(this.payChannelTypeList);
      } else {
        this.payChannelTypeList = [];
      }
      // this.commandForm.payType = "";
    },
    getDayList() {
      this.$http
        .post("/api/orderStream/gatherOrderByDay", {
          requestTime: this.commandForm.date ? this.commandForm.date : "",
          payformChannel: this.commandForm.channel,
          // payType: this.commandForm.payType,
          payformType: this.commandForm.transactioType,
          onlyShowSelft: this.commandForm.onlyShowSelft,
        })
        .then((res) => {
          if (res.code === "0000") {
            //console.log(res.data);
            this.info = res.data || {};
            this.dataList = res.data.resultData;
          }
        });
    },
    getMonthList() {
      this.$http
        .post("/api/orderStream/gatherOrderByMonth", {
          requestTime: this.commandForm.date ? this.commandForm.date : "",
          payformChannel: this.commandForm.channel,
          // payType: this.commandForm.payType,
          payformType: this.commandForm.transactioType,
          onlyShowSelft: this.commandForm.onlyShowSelft,
        })
        .then((res) => {
          if (res.code === "0000") {
            this.info = res.data || {};
            this.dataList = res.data.resultData;
          } else {
            this.dataList = [];
          }
        });
    },
  },
};
</script>

<style scoped lang="scss">
.width512 {
  width: 400px;
}
.cardDialog {
  .addTitle {
    font-size: 20px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: bold;
    color: rgba(0, 0, 0, 0.85);
  }
  .tip {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.65);
    margin-top: 12px;
    margin-bottom: 30px;
    span {
      color: #03bfc6;
    }
  }
  .tip1 {
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #869daa;
    // line-height: 17px;
  }
  :deep(.el-form-item--small.el-form-item:nth-of-type(2)) {
    margin-bottom: 0;
  }
  :deep(.el-dialog) {
    border-radius: 16px;
  }
  :deep(.el-dialog__body) {
    padding: 10px 40px;
    padding-bottom: 60px;
  }
  :deep(.el-button--small) {
    width: 74px;
  }
  :deep(.el-input__inner) {
    padding-left: 12px;
  }
  :deep(.el-form-item__content) {
    position: relative;
  }
  .form-img {
    width: 22px;
    border-radius: 22px;
    position: absolute;
    top: 5px;
    left: 10px;
    z-index: 1;
  }
}
.switch {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.ml {
  margin-left: 50px;
}
</style>
